package com.gao.service.impl;

import com.gao.entity.Product;
import com.gao.exception.ProductException;
import com.gao.mapper.ProductMapper;
import com.gao.service.ProductService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.gao.exception.ProductException.ErrorCode.*;

/**
 * @author gao
 * @time 2022/11/25 11:24:54
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {
    @NonNull
    private ProductMapper productMapper;

    @Override
    public Product findByProductId(Integer productId) {
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            throw new ProductException(PRODUCT_NOT_FOUND, productId);
        }
        return product;
    }

    @Override
    public Integer deductStock(Integer productId, Integer quantity) {
        Product product = findByProductId(productId);
        if (product.getStock() < quantity) {
            throw new ProductException(STOCK_NOT_ENOUGH, productId, quantity, product.getStock());
        }
        product.setStock(product.getStock() - quantity);
        productMapper.updateByPrimaryKey(product);
        return product.getStock();
    }

    @Override
    public List<Product> findByProductIds(List<Integer> productIds) {
        List<Product> products = new ArrayList<>();
        productIds.forEach(productId -> {
            products.add(findByProductId(productId));
        });
        return products;
    }
}
